import { Directive, ElementRef, OnInit, OnDestroy, HostBinding, Input } from '@angular/core';
import { DomTrackerService } from './dom-tracker.service';

@Directive({
  selector: '[appDomTracker]'
})
export class DomTrackerDirective implements OnInit, OnDestroy {

  @Input() appDomTrackerId: any;

  constructor(
    private el: ElementRef,
    private domTrackerService: DomTrackerService
  ) {

  }

  ngOnInit(): void {

    this.domTrackerService.trackCreated(this.appDomTrackerId);

  }

  ngOnDestroy(): void {

    this.domTrackerService.trackDestroyed(this.appDomTrackerId);

  }
}



import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

interface DomStats {
  created: number;
  destroyed: number;
  reused: number;
}

@Injectable({
  providedIn: 'root'
})
export class DomTrackerService {
  private _domStats = new BehaviorSubject<DomStats>({ created: 0, destroyed: 0, reused: 0 });
  domStats$: Observable<DomStats> = this._domStats.asObservable();




  private activeElementIds = new Set<any>();

  constructor() {

  }

  trackCreated(id: any): void {
    const currentStats = this._domStats.getValue();
    currentStats.created++;
    this.activeElementIds.add(id);
    this.updateStats(currentStats);
  }

  trackDestroyed(id: any): void {
    const currentStats = this._domStats.getValue();
    currentStats.destroyed++;
    this.activeElementIds.delete(id);
    this.updateStats(currentStats);
  }












  private updateStats(stats: DomStats): void {





    this._domStats.next({ ...stats, reused: stats.created - stats.destroyed });
  }

  resetStats(): void {
    this._domStats.next({ created: 0, destroyed: 0, reused: 0 });
    this.activeElementIds.clear();
    console.log('DomTrackerService: Stats reset.');
  }

  getStats(): DomStats {
    return this._domStats.getValue();
  }
}